import {
    atom,
    selector,
    useRecoilState,
    useRecoilValue,
    useRecoilValueLoadable,
    useRecoilSnapshot,
    RecoilRoot
} from 'recoil';



const todoListState = atom({
    key: 'todoListState',
    default: [
        {
            id: +new Date(),
            value: 'init',
            isComplete: false
        }
    ],
})

const todoListFilterState = atom({
    key: 'todoListFilterState',
    default: 'Show All',
});

function getList() {
    return fetch('/mock/todoList.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (myJson) {
            console.log(myJson);
            return myJson;
        })
}

const filteredTodoListState = selector({
    key: 'filteredTodoListState',
    get: ({get}) => {
        const filter = get(todoListFilterState);
        const list = get(todoListState);
        // if (list.length === 0) {
        //     useRecoilValueLoadable(getList())
        // }
        switch (filter) {
            case 'Show Completed':
                return list.filter((item) => item.isComplete);
            case 'Show Uncompleted':
                return list.filter((item) => !item.isComplete);
            default:
                return list;
        }
    },
});

const todoListStatsState = selector({
    key: 'todoListStatsState',
    get: ({get}) => {
        const todoList = get(todoListState);
        const totalNum = todoList.length;
        const totalCompletedNum = todoList.filter((item) => item.isComplete).length;
        const totalUncompletedNum = totalNum - totalCompletedNum;
        const percentCompleted = totalNum === 0 ? 0 : totalCompletedNum / totalNum;

        return {
            totalNum,
            totalCompletedNum,
            totalUncompletedNum,
            percentCompleted,
        };
    },
});


export {
    todoListStatsState,
    filteredTodoListState,
    todoListFilterState,
    todoListState,
    atom,
    selector,
    useRecoilState,
    useRecoilValue,
    useRecoilValueLoadable,
    useRecoilSnapshot,
    RecoilRoot
}
